package com.ys.chatserver.http.file.d;

import com.alibaba.fastjson.JSONObject;
import com.eva.epc.common.util.CommonUtils;
import com.eva.framework.httpfile.FileDownload;
import com.eva.framework.utils.LoggerFactory;
import com.ys.chatserver.BaseConf;
import com.ys.chatserver.http.logic.filter.JwtHelper;
import com.ys.chatserver.http.logic.filter.JwtParam;
import com.ys.chatserver.tool.EmptyUtils;
import com.ys.chatserver.tool.MD5Util;
import org.slf4j.Logger;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 群云盘视频下载
 *
 * @author Qxin
 */
public class CloudVideoDownloader extends HttpServlet implements Servlet {

    private static final Logger logger = LoggerFactory.getLog();

    public CloudVideoDownloader() {
    }

    private static final long serialVersionUID = 1L;


    protected void service(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        LoggerFactory.getLog().debug("[HTTP]下载云盘视频：你传过来的参数" +
                "group_id=" + req.getParameter("group_id")
                + ",file_name=" + req.getParameter("file_name")
                + ",is_thumb=" + req.getParameter("is_thumb")
                + ",[---- " + req.getContextPath() + "-" + req.getRequestURL() + "]");

        String file_name = req.getParameter("file_name");
        String group_id = req.getParameter("group_id");
        boolean is_thumb = Boolean.parseBoolean(req.getParameter("is_thumb"));
        if (is_thumb) {
            String token = req.getHeader("token");
            String time = req.getHeader("time");
            String authToken = req.getHeader("authToken");
            String path = String.format("/api/%s?%s", getServletName(), req.getQueryString());
            Map<String, String> map = new HashMap<>();
            map.put("token", token);
            map.put("time", time);
            map.put("path", path);
            String s = MD5Util.MD5_32(JSONObject.toJSONString(map));
            if (authToken == null) {
                return;
            }
            if (!authToken.equals(s)) {
                return;
            }
            if (EmptyUtils.isNotEmpty(token)) { //token校验
                JwtParam jwtParam = JwtHelper.parseJwt(token);
                String userUid = jwtParam.getUserId();
                try {
                    if (JwtHelper.tokenAuth(jwtParam)) {
                        if (!file_name.startsWith("record/")) {
                            processCloudVideoDownload(res, userUid, BaseConf.getInstance().getDIR_CLOUD_VIDEO_UPLOAD(), file_name, group_id, is_thumb, false);
                        } else {
                            processCloudVideoDownload(res, userUid, BaseConf.getInstance().getDIR_CLOUD_LIVE_VIDEO_UPLOAD(), file_name, null, is_thumb, true);
                        }
                    }
                } catch (Exception e) {
                    logger.error("无权限访问");
                }
            } else {
                logger.error("无权限访问");
            }
        } else {
            String userUid = req.getParameter("user_uid");
            if (!file_name.startsWith("record/")) {
                processCloudVideoDownload(res, userUid, BaseConf.getInstance().getDIR_CLOUD_VIDEO_UPLOAD(), file_name, group_id, is_thumb, false);
            } else {
                processCloudVideoDownload(res, userUid, BaseConf.getInstance().getDIR_CLOUD_LIVE_VIDEO_UPLOAD(), file_name, null, is_thumb, true);
            }
        }


    }

    /**
     * HTTP云盘视频文件下载实现方法.
     * <p>
     * 本方法没有任何异常地返回即意味着成功处理完成.
     *
     * @param file_dir 要下载的文件所位于的服务器磁盘目录（此dir的结尾需要"/"哦）
     * @param file_name 要下载的短视频真正文件名（此文件名主要是用于显示时，不是磁盘上的物理文件名哦），客户端下载时读取到的文件名就是本参数
     * @param group_Id  群id
     * @param isThumb   是否为首帧图
     */
    private void processCloudVideoDownload(HttpServletResponse res
            , String userUid, String file_dir, String file_name, String group_Id, boolean isThumb, Boolean isLiveFile) throws
            IOException {
        try {
            if (!CommonUtils.isStringEmpty(file_name, true)) {
                LoggerFactory.getLog().debug("[HTTP]用户【" + userUid + "】要下载的云盘视频文件 " + file_name
                        + "将立即开始处理过程 ......");
                // 实施文件下载
                if (!isLiveFile) {

                    FileDownload.download(res, String.format(file_dir, group_Id) + file_name, file_name, isThumb ? FileDownload.CONTENT_TYPE_JPEG : FileDownload.CONTENT_TYPE_MP4, false);
                } else {
                    FileDownload.download(res, file_dir + file_name, file_name, isThumb ? FileDownload.CONTENT_TYPE_JPEG : FileDownload.CONTENT_TYPE_MP4, false);

                }
            } else
                LoggerFactory.getLog().warn("[HTTP]对不起,用户【" + userUid + "】要下载的云盘视频文件(file_name=" + file_name + ")不存在！");
        } catch (Exception e) {
            LoggerFactory.getLog().warn("[HTTP]用户【" + userUid + "】的下载的云盘视频文件不存在，本次下次已提前结束(" + e.getMessage() + ")");
        }
    }

}
